# -*- coding: utf-8 -*-
# @Time    : 2016/9/27
from sympy import solve, Eq
from mathsolver.functions.daoshu.daoshuyunsuan import HanShuDaoShuYunSuan
from mathsolver.functions.hanshu.helper import check_func
from mathsolver.functions.base import BaseValue, BaseSymbolValue, new_latex
from mathsolver.functions.zhixian.property import GetQingXieJiao, GetXieLv003
from mathsolver.functions.base import BaseFunction


class QieXianQingXieJiao001(BaseFunction):
    """利用导数解决切线倾斜角问题"""

    def solver(self, *args):
        func = check_func(args[0])
        point = args[1]
        x1, x2 = point.sympify()

        # 求出曲线的导数
        daoshu = HanShuDaoShuYunSuan().solver(func)
        self.steps.extend(daoshu.steps)

        # 求出曲线导函数在某点处的导数值，即为切线的斜率
        deriv = daoshu.output[0]
        xielu = deriv.expression.subs(deriv.var, x1)
        self.steps.append(["把 {} = {} 代入上式，得到切线斜率为 k = {}".format(func.var, x1, xielu), ""])

        # 由切线斜率求出倾斜角
        qingxiejiao = GetQingXieJiao().solver(BaseValue(xielu))
        self.steps.append(["所以倾斜角为 {}".format(qingxiejiao.output[0].printing()), ""])

        self.output.append(qingxiejiao.output[0])
        self.label.add("利用导数解决切线倾斜角")
        return self


class QieXianQingXieJiao002(BaseFunction):
    """利用导数解决切线倾斜角问题"""

    def solver(self, *args):
        func = args[0]
        point, qingxiejiao = args[1:]
        x1, x2 = point.sympify()

        # 求出曲线的导数
        qiudao = HanShuDaoShuYunSuan().solver(func)
        self.steps.extend(qiudao.steps)
        deriv = qiudao.output[0]

        # 由切线倾斜角求出斜率
        xielu = GetXieLv003().solver(qingxiejiao).output[0]
        self.steps.append(["由倾斜角求出切线斜率为 {}".format(xielu.printing()), ""])

        # 列出方程（组）
        f_left = func.expression.subs(func.var, x1)
        f_d_left = deriv.expression.subs(deriv.var, x1)
        self.steps.append([r"由条件得 \left\{{\\begin{{matrix}} {0}({1}) = {2}  \\ {0}'({1}) = {3}  \end{{matrix}}\right."
                          .format(func.name, new_latex(x1), new_latex(x2), xielu.printing()),
                           r"即 \left\{{\begin{{matrix}} {} = {}  \\ {} = {}  \end{{matrix}}\right."
                          .format(new_latex(f_left), x2, new_latex(f_d_left), xielu.printing())])

        # 解方程（组）
        result = solve([Eq(f_left, x2), Eq(f_d_left, xielu.sympify())])
        self.steps.append(
            ["解得 " + " 或 ".join(["{} = {}".format(key, value) for m in result for key, value in m.items()]), ""])

        aa = result[0].keys()
        self.output.append(
            BaseSymbolValue({tuple(var for var in aa): [tuple(item.values()) for item in result]}))
        self.label.add("利用导数解决切线倾斜角")
        return self


if __name__ == "__main__":
    pass
